﻿using System;
using System.Text.RegularExpressions;
using BloggerAutoPosterService.Engine.Core;
using BloggerAutoPosterService.Engine.Net;
using Google.GData.Client;

namespace BloggerAutoPosterService.Engine.Utils
{
    public static class UrlUtils
    {
        #region Methods

        // Public Methods

        public static string FindOrigianlLink(IServiceConfig serviceConfig, IRedirectFinder redirectFinder, string url)
        {
            if (!url.ToLowerInvariant().Contains("feedproxy.google.com")) return url;

            try
            {
                redirectFinder.Url = url;
                return redirectFinder.GetRedirectUrl();
            }
            catch (Exception ex)
            {
                new Logger(serviceConfig).WriteLine(ex);
            }

            return url;
        }

        public static string RemoveEmailPart(this string data)
        {
            if (string.IsNullOrWhiteSpace(data)) return string.Empty;

            const string pattern = @"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
            return Regex.Replace(data, pattern, string.Empty).Trim();
        }

        public static string TrimFeedburnerPart(this string url)
        {
            var idx = url.ToLowerInvariant().IndexOf("utm_source=");
            return idx == -1 ? url : url.Substring(0, idx - 1);
        }

        public static string HtmlDecode(this string data)
        {
            if (string.IsNullOrWhiteSpace(data)) return string.Empty;
            return HttpUtility.HtmlDecode(data);
        }

        #endregion Methods
    }
}
